package org.railage.server.dao;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.railage.server.util.HibernateUtil;

public class TicketDAOImpl implements TicketDAO {

	private static final Logger log = Logger
			.getLogger(StationOfRouteDAOImpl.class);

	public int sellTicket(int userID, int tripID, String stationA,
			String stationB) {
		Session session = null;
		Transaction transaction;
		int result = -1;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			transaction = session.beginTransaction();
			Query query = session
					.createSQLQuery("select fn_sell_ticket(:userID, :tripID, :stationA, :stationB)");
			query.setInteger("userID", userID);
			query.setInteger("tripID", tripID);
			query.setString("stationA", stationA);
			query.setString("stationB", stationB);
			result = (Integer) query.uniqueResult();
			transaction.commit();
		} catch (Exception e) {
			log.error("Error occured during Hibernate session:", e);
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return result;
	}

	public int getAvailableTicketsNumber(int tripID, String stationA,
			String stationB) {
		Session session = null;
		int result = -1;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			Query query = session
					.createSQLQuery("select fn_get_available_seats_count(:tripID, :stationA, :stationB)");
			query.setInteger("tripID", tripID);
			query.setString("stationA", stationA);
			query.setString("stationB", stationB);
			result = (Integer) query.uniqueResult();
		} catch (Exception e) {
			log.error("Error occured during Hibernate session:", e);
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return result;
	}
}
